package com.visitor.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.visitor.bean.SmartUser;
import com.visitor.mapper.SmartUserMapper;
import com.visitor.utils.DateUtils;
import com.visitor.web.vm.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SmartUserService {
	@Resource
	private SmartUserMapper smartUserMapper;

	@Transactional
	public Response<String> saveOrUpdate(SmartUser user) {
			if(user.getId()!=null) {
				SmartUser isExtis=smartUserMapper.isExtis(user);
				if(null!=isExtis){
					return Response.error(300);
				}else{
					smartUserMapper.updateByPrimaryKey(user);
					return Response.ok();
				}
			}else {
				SmartUser search=new SmartUser();
				search.setPhone(user.getPhone());
				search.setAccount(user.getAccount());
				search=smartUserMapper.isExtis(search);
				if(null!=search){
					return Response.error(300);
				}else{
					user.setCreateTime(DateUtils.getTime());
					smartUserMapper.insert(user);
					return Response.ok();
				}
			}
	}

	public SmartUser findUserById(Long id) {
		SmartUser user = smartUserMapper.selectByPrimaryKey(id);
		return user;
	}

	public SmartUser login(SmartUser user) {
		return smartUserMapper.selectByParam(user);
	}
	
	public int deleteUserById(Long id) {
		return smartUserMapper.deleteByPrimaryKey(id);
	}
	
	public PageInfo<SmartUser> getAllByPage(int pageNum,int pageSize,SmartUser user){
		PageHelper.startPage(pageNum, pageSize, true);
		List<SmartUser> list= smartUserMapper.selectAll(user);
		if(list==null||list.isEmpty()) {
			list = new ArrayList<>();
		}
		return new PageInfo<>(list);
	}
}
